package lock_thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/29
 * Time:20:49
 * lock加锁
 **/
public class Demo2 {
    //全局变量
    private static int number = 0;
    //循环次数
    public static final int maxSize = 100000;

    public static void main(String[] args) throws InterruptedException {
        //1.创建手动锁
        Lock lock = new ReentrantLock();
        //+10W
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < maxSize; i++) {
                    //2.加锁
                    lock.lock();
                    try {
                        number++;
                    } finally {
                        //3.释放锁
                        lock.unlock();
                    }
                }
            }
        });
        t1.start();

        //-10W
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < maxSize; i++) {
                    //2.加锁
                    lock.lock();
                    try {
                        number--;
                    } finally {
                        //3.释放锁
                        lock.unlock();
                    }
                }
            }
        });
        t2.start();

        //等待线程1 和线程2 执行完
        t1.join();
        t2.join();

        System.out.println("最终执行结果" + number);
    }
}
